package com.djmw.mouse.service;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;
import org.springside.modules.persistence.SearchFilter.Operator;

import com.djmw.mouse.entity.PositionHistory;
import com.djmw.mouse.repository.PositionHistoryDao;

//Spring Bean的标识.
@Component
// 默认将类中的所有public函数纳入事务管理.
@Transactional(readOnly = true)
public class PositionHistoryService {

	@Autowired
	private PositionHistoryDao positionHistoryDao;

	public PositionHistory getPositionHistory(Long id) {
		return positionHistoryDao.findOne(id);
	}

	@Transactional(readOnly = false)
	public void savePositionHistory(PositionHistory entity) {
		positionHistoryDao.save(entity);
	}

	public Page<PositionHistory> getPositionHistory(Long positionId, Map<String, Object> searchParams, int pageNumber,
			int pageSize, String sortDir) {
		PageRequest pageRequest = buildPageRequest(pageNumber, pageSize, sortDir);
		Specification<PositionHistory> spec = buildSpecification(positionId, searchParams);

		return positionHistoryDao.findAll(spec, pageRequest);
	}

	/**
	 * 创建分页请求.
	 */
	private PageRequest buildPageRequest(int pageNumber, int pagzSize, String sortDir) {
		Sort sort = new Sort("d".equals(sortDir) ? Direction.DESC : Direction.ASC, "recordDate");
		return new PageRequest(pageNumber - 1, pagzSize, sort);
	}

	/**
	 * 创建动态查询条件组合.
	 */
	private Specification<PositionHistory> buildSpecification(Long positionId, Map<String, Object> searchParams) {
		Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
		filters.put("position.id", new SearchFilter("position.id", Operator.EQ, positionId));
		Specification<PositionHistory> spec = DynamicSpecifications.bySearchFilter(filters.values(),
				PositionHistory.class);
		return spec;
	}

}
